﻿using System;
using System.Diagnostics;
using System.Reflection;
using Common.Logging;

namespace SpCop
{
    public class MethodTimer : IDisposable
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof (MethodTimer));

        private readonly DateTime _start;
        private readonly string _title;


        public MethodTimer()
        {
            var currentMethod = MethodBase.GetCurrentMethod();
            _title = currentMethod != null ? currentMethod.Name : "Untitled";
            _start = DateTime.Now;
        }

        public MethodTimer(string title)
        {
            _title = title;
            _start = DateTime.Now;
        }

        #region IDisposable Members

        public void Dispose()
        {
            Dispose(true);
        }

        #endregion

        private void Dispose(bool disposing)
        {
            if (!disposing)
                return;


            TimeSpan timeSpan = DateTime.Now.Subtract(_start);
            if (timeSpan.TotalSeconds < 5)
            {
                Log.Info(m => m("{1} Took : {0} ms", Math.Round(timeSpan.TotalMilliseconds, 2), _title));
            }
            else
            {
                Log.Info(m => m("{1} Took : {0} sec", Math.Round(timeSpan.TotalSeconds, 2), _title));
            }

            GC.SuppressFinalize(this);
        }

        ~MethodTimer()
        {
            Dispose(false);
        }
    }
}